Page({
    data: {
      openid: '',
      avatarUrl: '/images/setting/images.png',
      fullName: '',
      phone: '',
      address: '',
      genderOptions: ['男', '女', '保密'],
      genderIndex: 2, // 默认保密
      countryCodes: ['+86', '+1', '+44', '+81', '+33'],
      countryFlags: [
        '/images/flags/cn.png',
        '/images/flags/us.png',
        '/images/flags/uk.png',
        '/images/flags/jp.png',
        '/images/flags/fr.png'
      ],
      countryCodeIndex: 0
    },
  
    onShow() {
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo || !userInfo.openid) {
        wx.showModal({
          title: '未登录',
          content: '请先登录才能查看和编辑个人资料',
          showCancel: false,
          success: () => {
            wx.navigateBack();
          }
        });
        return;
      }
      this.setData({ openid: userInfo.openid });
      this.fetchProfile();
    },
  
    fetchProfile() {
      wx.request({
        url: `http://localhost:3000/user/profile?openid=${this.data.openid}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            const data = res.data.data;
            console.log(data);
            this.setData({
              avatarUrl: data.avatarUrl || '/images/avatar_default.png',
              fullName: data.fullName || '',
              phone: data.phone || '',
              address: data.address || '',
              genderIndex: data.gender || 2
            });
          } else {
            wx.showToast({ title: res.data.message || '获取资料失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.showToast({ title: '请求失败，请检查网络', icon: 'none' });
        }
      });
    },
  
    onInputName(e) {
      this.setData({ fullName: e.detail.value });
    },
  
    onGenderChange(e) {
      this.setData({ genderIndex: e.detail.value });
      console.log('选中性别索引:', e.detail.value, '性别:', this.data.genderOptions[e.detail.value]);
    },
  
    onCountryCodeChange(e) {
      this.setData({ countryCodeIndex: e.detail.value });
    },
  
    onInputPhone(e) {
      this.setData({ phone: e.detail.value });
    },
  
    onLocateAddress() {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success: () => {
                this.openMap();
              },
              fail: () => {
                wx.showModal({
                  title: '需要授权定位',
                  content: '请在设置中开启定位权限',
                  success: () => {
                    wx.openSetting();
                  }
                });
              }
            });
          } else {
            this.openMap();
          }
        }
      });
    },
  
    openMap() {
      wx.chooseLocation({
        success: (res) => {
          this.setData({ address: res.address });
        },
        fail: () => {
          wx.showToast({ title: '定位失败', icon: 'none' });
        }
      });
    },
  
    previewAvatar() {
      wx.previewImage({
        current: this.data.avatarUrl,
        urls: [this.data.avatarUrl]
      });
    },
  
    onEditAvatar() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.setData({ avatarUrl: tempFilePath });
          // TODO: 上传到服务器获取远程URL
        },
        fail: (err) => {
          console.log('选择头像失败', err);
        }
      });
    },
  
    onSaveProfile() {
        if (!this.data.openid) {
          wx.showToast({ title: '未登录，无法保存', icon: 'none' });
          return;
        }
      
        const trimmedName = this.data.fullName.trim();
        const namePattern = /^[\u4e00-\u9fa5a-zA-Z\s·.]{1,20}$/;
      
        // 姓名校验
        if (trimmedName.length === 0) {
          wx.showToast({ title: '请输入姓名', icon: 'none' });
          return;
        }
        if (trimmedName.length > 20) {
          wx.showToast({ title: '姓名不能超过20个字符', icon: 'none' });
          return;
        }
        if (!namePattern.test(trimmedName)) {
          wx.showToast({ title: '姓名不能含特殊符号', icon: 'none' });
          return;
        }
      
        // 手机号校验
        const phonePattern = /^[0-9]{5,15}$/;
        if (!this.data.phone || !phonePattern.test(this.data.phone)) {
          wx.showToast({ title: '请输入有效手机号', icon: 'none' });
          return;
        }
      
        // 性别索引校验
        if (this.data.genderIndex < 0 || this.data.genderIndex >= this.data.genderOptions.length) {
          wx.showToast({ title: '性别选择不正确', icon: 'none' });
          return;
        }
      
        wx.request({
          url: 'http://localhost:3000/user/profile',
          method: 'POST',
          data: {
            openid: this.data.openid,
            avatarUrl: this.data.avatarUrl,
            fullName: trimmedName,
            phone: this.data.phone,
            address: this.data.address,
            gender: this.data.genderIndex
          },
          success: (res) => {
            if (res.data.code === 200) {
              wx.showToast({ title: '资料已保存', icon: 'success' });
            } else {
              wx.showToast({ title: res.data.message || '保存失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '请求失败，请检查网络', icon: 'none' });
          }
        });
      },
  
    goBack() {
      wx.navigateBack();
    }
  });
  